import { useUserStore } from "@/store/modules/user";
import { useClipboard } from "@vueuse/core";
import { ref } from "vue";
const clipboardSource = ref("");
const { copy, copied, isSupported } = useClipboard({
  source: clipboardSource,
  legacy: true,
});

function getValue(obj, path) {
  if (!obj || !path) return "";
  const keys = path.split(".");

  function resolve(current, keys) {
    if (keys.length === 0) return current;
    const key = keys[0];
    const remainingKeys = keys.slice(1);

    // 如果当前值是数组，递归处理每个元素并返回数组
    if (Array.isArray(current)) {
      return current.map((item) => resolve(item, remainingKeys)).flat(Infinity);
    }

    // 如果当前值是null或undefined，返回空字符串
    if (current === null || current === undefined) return "";

    // 递归处理对象属性
    return resolve(current[key], remainingKeys);
  }

  return resolve(obj, keys);
}
import { storeToRefs } from "pinia";
import { EleMessage } from "ele-admin-plus/es";

/**
 * 从VNode中提取文本内容
 * @param {VNode} vnode - Vue虚拟节点
 * @returns {string} 提取的文本
 */
export const getTextFromVNode = (vnode) => {
  if (!vnode) return "";
  if (Array.isArray(vnode)) {
    return vnode.map((item) => getTextFromVNode(item)).join("");
  }
  if (typeof vnode === "string") return vnode;
  if (vnode?.props?.innerHTML) return vnode.props.innerHTML;

  // 处理自定义组件
  if (typeof vnode?.type === "object" && vnode?.type?.name) {
    let text = "";
    // 处理带字典code的组件
    if (vnode?.props?.code) {
      const userStore = useUserStore();
      const { dicts } = storeToRefs(userStore);
      const dictOptions = dicts.value[vnode.props.code] || [];
      const targetOption = dictOptions.find(
        (option) => option.dict_data_code == vnode.props.modelValue,
      );
      text = targetOption?.dict_data_name || vnode.props.modelValue;
    } else {
      // 其他组件优先从props获取text或value
      text = vnode?.props?.text || vnode?.props?.value;
    }

    // 从插槽获取内容
    if (!text && vnode?.children) {
      if (typeof vnode.children === "function") {
        const slotVNodes = vnode.children();
        text = getTextFromVNode(slotVNodes);
      } else if (
        vnode.children.default &&
        typeof vnode.children.default === "function"
      ) {
        const slotVNodes = vnode.children.default();
        text = getTextFromVNode(slotVNodes);
      } else {
        text = getTextFromVNode(vnode.children);
      }
    }

    // 清理HTML标签
    if (text && /<[^>]+>/g.test(text)) {
      const div = document.createElement("div");
      div.innerHTML = text;
      text = div.textContent || div.innerText || "";
    }

    return text || "";
  }

  // 处理子节点
  if (vnode?.children) {
    return Array.isArray(vnode.children)
      ? vnode.children.map((child) => getTextFromVNode(child)).join("")
      : getTextFromVNode(vnode.children);
  }

  return "";
};

/**
 * 创建双击复制处理函数
 * @param {Object} options - 配置选项
 * @param {Object} options.slotProps - 插槽属性
 * @param {Object} options.col - 列配置
 * @param {Object} options.slots - 插槽对象
 * @returns {Function} 双击处理函数
 */
export function renderCopyableContent({
  slotProps,
  col,
  slots,
  ownSlots,
  props,
  renderTableColumn,
  isCopyOnly = false,
}) {
  const handleDblClick = createCopyHandler({
    slotProps,
    col,
    slots,
    isCopyOnly,
  });

  const content =
    col.slot &&
    !ownSlots.includes(col.slot) &&
    slots[col.slot] &&
    (!props.slotNormalize || slotProps?.$index != -1)
      ? slots[col.slot]?.(slotProps)
      : col.children && col.children.length
        ? col.children.map(renderTableColumn)
        : col.formatter && typeof col.formatter === "function"
          ? col.formatter(
              slotProps.row,
              slotProps.column,
              getValue(slotProps.row, slotProps.column.property),
              slotProps.$index,
            )
          : getValue(slotProps.row, slotProps.column.property) || "";

  return typeof content === "object" ? (
    <div onDblclick={handleDblClick}>{content}</div>
  ) : (
    <span onDblclick={handleDblClick} class="ele-cell-content">
      {content}
    </span>
  );
}

export const createCopyHandler = ({ slotProps, col, slots, isCopyOnly }) => {
  return () => {
    let text;
    if (isCopyOnly) {
      text = getValue(slotProps.row, slotProps.column.property);
    } else if (
      col.slot &&
      !["default", "append", "empty"].includes(col.slot) &&
      slots[col.slot]
    ) {
      const slotResult = slots[col.slot]?.(slotProps);
      text = getTextFromVNode(slotResult) || "";

      // 如果从模板获取的内容为空，继续执行后续判断
      if (!text) {
        if (col.formatter && typeof col.formatter === "function") {
          text = col.formatter(
            slotProps.row,
            slotProps.column,
            slotProps.row[slotProps.column.property],
            slotProps.$index,
          );
        } else {
          // 支持嵌套属性访问
          text = getValue(slotProps.row, slotProps.column.property);
          // 如果是数组则拼接为字符串
          if (Array.isArray(text)) {
            text = text.join(", ");
          }
        }
      }
    } else if (col.formatter && typeof col.formatter === "function") {
      text = col.formatter(
        slotProps.row,
        slotProps.column,
        slotProps.row[slotProps.column.property],
        slotProps.$index,
      );
    } else {
      text = getValue(slotProps.row, slotProps.column.property);
    }

    if (text !== undefined && text !== null) {
      console.log("复制内容", text);
      clipboardSource.value = String(text);
      if (isSupported) {
        copy().then(() => {
          console.log("复制成功", copied.value);
          EleMessage[copied.value ? "success" : "error"](
            copied.value ? "复制成功" : "复制失败",
          );
        });
      } else {
        EleMessage.error("您的浏览器不支持复制功能");
      }
    }
  };
};
